import pymysql
from dotenv import load_dotenv
import os
import hashlib

# 加载环境变量
load_dotenv()

def hashlib_password(password):
    """简单的密码哈希函数"""
    return hashlib.md5(password.encode('utf-8')).hexdigest()

try:
    # 连接到zpsjfx数据库
    conn = pymysql.connect(
        host='localhost',
        port=3306,
        user='root',
        password='123456',
        database='zpsjfx'
    )
    
    with conn.cursor() as cursor:
        # 插入新用户
        username = 'testuser'
        email = 'test@example.com'
        password = hashlib_password('password123')
        
        # 检查用户是否已存在
        cursor.execute("SELECT id FROM users WHERE username = %s OR email = %s", (username, email))
        existing_user = cursor.fetchone()
        
        if existing_user:
            print(f"用户 {username} 或邮箱 {email} 已存在")
        else:
            # 插入新用户
            sql = "INSERT INTO users (username, password, email) VALUES (%s, %s, %s)"
            cursor.execute(sql, (username, password, email))
            conn.commit()
            print(f"用户 {username} 注册成功")
            
            # 验证用户是否已插入
            cursor.execute("SELECT * FROM users WHERE username = %s", (username,))
            user = cursor.fetchone()
            if user:
                print(f"插入的用户: ID={user[0]}, 用户名={user[1]}, 邮箱={user[3]}")
            else:
                print("用户插入失败")
    
    conn.close()
    
except Exception as e:
    print(f"数据库操作失败: {e}")